package com.smritimap.demo.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.View;

/**
 * Created by zxn on 2024/12/17.
 */
public class CustomImageView extends View {
    private Drawable drawable;

    public CustomImageView(Context context) {
        super(context);
    }

    public CustomImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public CustomImageView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public void setImageDrawable(Drawable drawable) {
        this.drawable = drawable;
        invalidate(); // 请求重绘视图
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (drawable != null) {
            final int viewWidth = getWidth();
            final int viewHeight = getHeight();
            final int drawableWidth = drawable.getIntrinsicWidth();
            final int drawableHeight = drawable.getIntrinsicHeight();
            int drawX = (viewWidth - drawableWidth) / 2; // 计算绘制位置以居中
            int drawY = (viewHeight - drawableHeight) / 2;
            drawable.setBounds(drawX, drawY, drawX + drawableWidth, drawY + drawableHeight);
            drawable.draw(canvas); // 绘制Drawable
        }
    }

}
